package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCardMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderSubmitService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderSubmitServiceImpl implements OrderSubmitService {

    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCardMapper shoppingCardMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional
    @Override
    /*用户下单*/
    public OrderSubmitVO submitOrder(OrdersSubmitDTO orderSubmitDto) {


        // 处理业务异常（地址簿为空，购物车数据为空）
        AddressBook addressBook = addressBookMapper.getAddressBookById(orderSubmitDto.getAddressBookId());
        String address = addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail();
        checkOutOfRange(address);
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCard = new ShoppingCart();
        shoppingCard.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> lists = shoppingCardMapper.list(shoppingCard);
        if(lists.size() == 0 || lists == null){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 向订单表提交一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderSubmitDto, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddress(address);
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.insert(orders);
        // 向订单明细表插入n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for(ShoppingCart list : lists){
            OrderDetail orderDetail = new OrderDetail();  // 订单明细
            BeanUtils.copyProperties(list, orderDetail);
            orderDetail.setOrderId(orders.getId()); // 设置当前关联id
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertList(orderDetailList);

        // 清空购物车数据
        shoppingCardMapper.clean(shoppingCard);
        // 封装vo返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        return orderSubmitVO;
    }

    /*查询历史订单*/
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = orderMapper.historyOrders(ordersPageQueryDTO);

        List<Orders> orders = page.getResult();
        List<OrderVO> list = new ArrayList<>();
        if(page.getTotal()>0){
            for(Orders order : orders){
                // 查询订单详情
                List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(order.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /*根据id查询订单详情*/
    public OrderVO getDetailById(Long id) {
        // 查询订单表
        Orders orders = orderMapper.selectOrderById(id);
       // 获取订单详情的id
        Long ordersId= orders.getId();
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(ordersId);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void cancelOrder(Long id) {
        // 根据id查询订单
        Orders orders = orderMapper.selectOrderById(id);

        // 检验订单是否存在
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 修改订单状态
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    @Override
    public void againOrder(Long id) {
        // 查询订单详情
        List<OrderDetail> orderDetaillist = orderDetailMapper.selectByOrderId(id);
        // 将订单详情对象转换为购物车对象
        for(OrderDetail orderDetail : orderDetaillist){
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            // 将购物车对象添加到对应用户的购物车中
            shoppingCardMapper.insert(shoppingCart);
        }

    }

    @Override
    public PageResult pageSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.historyOrders(ordersPageQueryDTO);

        // 获取订单信息
        List<Orders> ordersList =  page.getResult();
        List<OrderVO> list = new ArrayList<>();
        // 获取订单的详情信息
        for(Orders orders : ordersList){
            OrderVO orderVO = new OrderVO();
            // 复制订单信息
            BeanUtils.copyProperties(orders,orderVO);
            String orderDishes = getOrderDishesStr(orders);
            // 将菜品详情信息加入到orderVO中
            orderVO.setOrderDishes(orderDishes);
            // 添加到list中
            list.add(orderVO);
        }
        return new PageResult(page.getTotal(),list);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        // 查询所有订单
        List<Orders> ordersList =  orderMapper.selectAllOrder();
        // 定义变量
        Integer confirmed = 0;  // 待派送
        Integer delivery = 0;  // 派送中
        Integer toBeConfirmed = 0; //待接单
        for(Orders orders : ordersList){
            if(orders.getStatus() == Orders.CONFIRMED)
            {
                confirmed +=1;
            }else if(orders.getStatus() == Orders.DELIVERY_IN_PROGRESS){
                delivery += 1;
            }else if(orders.getStatus() == Orders.TO_BE_CONFIRMED){
                toBeConfirmed += 1;
            }
        }
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(delivery);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        return orderStatisticsVO;
    }

    /*查询订单的详细信息*/
    public OrderVO getOrder(Long id) {
        OrderVO orderVO = new OrderVO();
        // 查询订单信息
        Orders orders = orderMapper.selectOrderById(id);
        // 复制订单信息
        BeanUtils.copyProperties(orders,orderVO);
        // 获取订单详情id
        Long orderId =  orders.getId();
        // 查询订单详情信息
        List<OrderDetail> orderDetailList = orderDetailMapper.selectByOrderId(orderId);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    // 接单
    public void confirm(OrdersConfirmDTO ordersDTO) {
        ordersDTO.setStatus(Orders.CONFIRMED);
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersDTO,orders);
        orderMapper.update(orders);
    }

    // 拒单
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO,orders);
        // 设置订单状态为已拒绝
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    // 取消订单
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO,orders);
        // 更新订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    // 派送订单
    public void delivery(Long id) {
        // 根据id查询订单信息
        Orders orders = orderMapper.selectOrderById(id);
        // 校验订单是否存在，并且状态为3
        if (orders == null || !orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    // 完成订单
    public void complete(Long id) {
        // 根据id查询订单信息
        Orders orders = orderMapper.selectOrderById(id);
        // 检验订单是否存在，且状态为派送中
        if(orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 更新状态
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);

    }

    @Override
    public void reminder(Long id) {
        // 根据id查询订单信息
        Orders orders = orderMapper.selectOrderById(id);

        // 检验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", id); 
        map.put("content", "订单号：" + orders.getNumber());

        // 通过websocket向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
    // 将菜品信息转化为字符串
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品的详细信息
        List<OrderDetail> lists = orderDetailMapper.selectByOrderId(orders.getId());

        String str = "";
        // 将每一条菜品信息拼接成字符串
        for(OrderDetail list : lists){
            String orderDish = list.getName() + "*" + list.getNumber() + ";";
            // 将菜品拼接到一起
            str += orderDish;
        }
        return str;
    }


    /*检查用户的地址是否超过配送范围*/
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak",ak);

        // 获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("http://api.map.baidu.com/geocoding/v3/", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址有误");
        }

        // 数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");

        // 店铺的经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        // 获取用户收获地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("http://api.map.baidu.com/geocoding/v3/", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");

        // 用户收获地址的经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        // 路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/direction/v2/driving", map);
        jsonObject = JSON.parseObject(json);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            // 配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
